package com.spring.api.web.controller;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RandCodeImage extends HttpServlet{
	private static final long serialVersionUID = -1257947018545327308L;
    private static final String SESSION_KEY_OF_RAND_CODE = "randCode"; 
    /**
	 * 
	 */
	private static final int count = 200;

    /**
     */
    private static final int width = 105;
	/**
	 */
	private static final int height = 35;
	/**
	 */
	private static final int lineWidth = 2;

	@Override
	public void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// response.setContentType("image/png");

		final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		final Graphics2D graphics = (Graphics2D) image.getGraphics();

		graphics.setColor(Color.WHITE); // ---1
		graphics.fillRect(0, 0, width, height);
		graphics.drawRect(0, 0, width - 1, height - 1);

        final Random random = new Random();
		for (int i = 0; i < count; i++) {
			graphics.setColor(getRandColor(150, 200)); // ---3

			final int x = random.nextInt(width - lineWidth - 1) + 1; 
			final int y = random.nextInt(height - lineWidth - 1) + 1;
			final int xl = random.nextInt(lineWidth);
			final int yl = random.nextInt(lineWidth);
			graphics.drawLine(x, y, x + xl, y + yl);
		}

		final String resultCode = exctractRandCode();
		for (int i = 0; i < resultCode.length(); i++) {
			graphics.setColor(Color.BLACK);
            graphics.setFont(new Font("Times New Roman", Font.BOLD, 24));
			graphics.drawString(String.valueOf(resultCode.charAt(i)), (23 * i) + 8, 26);
		}
		request.getSession().setAttribute(SESSION_KEY_OF_RAND_CODE, resultCode);
		graphics.dispose();

		ImageIO.write(image, "JPEG", response.getOutputStream());
	}

	@Override
	public void doPost(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		doGet(request, response);
	}

	/**
	 */
	private String exctractRandCode() {
		final String randCodeType = "5";
        int randCodeLength = Integer.parseInt("4");
//        if (randCodeType == null) {
//			return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength);
//		} else {
			switch (randCodeType.charAt(0)) {
			case '1':
				return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength);
			case '2':
				return RandCodeImageEnum.LOWER_CHAR.generateStr(randCodeLength);
			case '3':
				return RandCodeImageEnum.UPPER_CHAR.generateStr(randCodeLength);
			case '4':
				return RandCodeImageEnum.LETTER_CHAR.generateStr(randCodeLength);
			case '5':
				return RandCodeImageEnum.ALL_CHAR.generateStr(randCodeLength);

			default:
				return RandCodeImageEnum.NUMBER_CHAR.generateStr(randCodeLength);
			}
//		}
	}

	/**
	 * ÃèÊö£º
	 * 
	 * @param fc
	 *            ÃèÊö£º
	 * @param bc
	 *            ÃèÊö£º
	 * 
	 * @return ÃèÊö£º
	 */
	private Color getRandColor(int fc, int bc) { // È¡µÃ¸ø¶¨·¶Î§Ëæ»úÑÕÉ«
		final Random random = new Random();
		if (fc > 255) {
			fc = 255;
		}
		if (bc > 255) {
			bc = 255;
		}

		final int r = fc + random.nextInt(bc - fc);
		final int g = fc + random.nextInt(bc - fc);
		final int b = fc + random.nextInt(bc - fc);

		return new Color(r, g, b);
	}
}

/**
 * ÑéÖ¤Âë¸¨ÖúÀà
 * 
 * @author ÕÅ¹úÃ÷ guomingzhang2008@gmail.com <br/>
 *         2012-2-28 ÏÂÎç2:15:14
 * 
 */
enum RandCodeImageEnum {
	ALL_CHAR("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"),
	LETTER_CHAR("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"),
	LOWER_CHAR("abcdefghijklmnopqrstuvwxyz"),
	NUMBER_CHAR("0123456789"),
	UPPER_CHAR("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
	private String charStr;
	private RandCodeImageEnum(final String charStr) {
		this.charStr = charStr;
	}

	/**
	 * 
	 * @param codeLength
	 */
	public String generateStr(final int codeLength) {
		final StringBuffer sb = new StringBuffer();
		final Random random = new Random();
		final String sourseStr = getCharStr();

		for (int i = 0; i < codeLength; i++) {
			sb.append(sourseStr.charAt(random.nextInt(sourseStr.length())));
		}

		return sb.toString();
	}

	/**
	 * @return the {@link #charStr}
	 */
	public String getCharStr() {
		return charStr;
	}
}
